python实现链表的反转递归

您所在的位置:网站首页 链表部分翻转 python python实现链表的反转递归

python实现链表的反转递归

2023-08-24 01:42| 来源: 网络整理| 查看: 265

def reverse (item, tail = None):

next = item.next

item.next = tail

if next is None:

return item

else:

return reverse(next, item)

使用这样一个简单的链表实现:

class LinkedList:

def __init__ (self, value, next = None):

self.value = value

self.next = next

def __repr__ (self):

return 'LinkedList({}, {})'.format(self.value, repr(self.next))

例:

>>> a = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4))))

>>> a

LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4, None))))

>>> b = reverse(a)

>>> b

LinkedList(4, LinkedList(3, LinkedList(2, LinkedList(1, None))))

>>> a # note that there is a new head pointer now

LinkedList(1, None)



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3